package com.kevin.data.batch.configuration;

import com.zaxxer.hikari.HikariDataSource;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;

@Configuration
@EnableBatchProcessing(modular = true)
public class DataBatchConfiguration {

    /**
     * 任务执行监听器
     */
    @Bean
    public BizJobListener jobListener() {
        return new BizJobListener();
    }

    /**
     * 业务数据处理器
     */
    @Bean
    public BizItemProcessor bizItemProcessor() {
        return new BizItemProcessor();
    }

    /**
     * 事务管理器
     */
    @Bean
    public PlatformTransactionManager transactionManager() {
        return new DataSourceTransactionManager(dataSource());
    }

    /**
     * SpringBatch 元数据库
     */
    @Bean("dataSource")
    public DataSource dataSource() {
        return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
                .addScript("/org/springframework/batch/core/schema-drop-h2.sql")
                .addScript("/org/springframework/batch/core/schema-h2.sql").build();
    }

    /**
     * 业务数据库
     */
    @Bean("bizDatasource")
    public DataSource bizDatasource() {
        HikariDataSource dataSource = new HikariDataSource();
        dataSource.setDriverClassName(bizDatasourceProperties().getDriverClassName());
        dataSource.setJdbcUrl(bizDatasourceProperties().getUrl());
        dataSource.setUsername(bizDatasourceProperties().getUsername());
        dataSource.setPassword(bizDatasourceProperties().getPassword());
        return dataSource;
    }

    /**
     * 业务数据库配置文件
     */
    @Bean("bizDatasourceProperties")
    @ConfigurationProperties(prefix = "spring.datasource")
    public BizDatasourceProperties bizDatasourceProperties() {
        return new BizDatasourceProperties();
    }

}
